package pers.dawnyang.config.filter.xss;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * xss过滤包装类
 * 
 * @author dawn yang
 * 
 */
public class XssRequestWrapper extends HttpServletRequestWrapper {
  private static final Logger logger = LoggerFactory.getLogger(XssRequestWrapper.class);

  public XssRequestWrapper(HttpServletRequest request) {
    super(request);
  }

  @Override
  public String getHeader(String name) {
    String strHeader = super.getHeader(name);
    if (StringUtils.isEmpty(strHeader)) {
      return strHeader;

    }
    return Jsoup.clean(super.getHeader(name), Whitelist.relaxed());
    // return HtmlUtils.htmlEscape(super.getHeader(name), "UTF-8");
  }

  @Override
  public String getParameter(String name) {
    String strParameter = super.getParameter(name);
    if (StringUtils.isEmpty(strParameter)) {
      return strParameter;
    }
    return Jsoup.clean(super.getParameter(name), Whitelist.relaxed());
    // return HtmlUtils.htmlEscape(super.getParameter(name), "UTF-8");
  }

  @Override
  public Map<String, String[]> getParameterMap() {
    Map<String, String[]> map = super.getParameterMap();
    Map<String, String[]> encodedMap = new HashMap<String, String[]>();
    for (Entry<String, String[]> entry : map.entrySet()) {
      int count = entry.getValue().length;
      String[] encodedValues = new String[count];
      for (int i = 0; i < count; i++) {
        encodedValues[i] = Jsoup.clean(entry.getValue()[i], Whitelist.relaxed());
        // encodedValues[i] = HtmlUtils.htmlEscape(entry.getValue()[i], "UTF-8");
      }
      encodedMap.put(entry.getKey(), encodedValues);
    }
    return encodedMap;
  }

  @Override
  public String[] getParameterValues(String name) {
    String[] values = super.getParameterValues(name);
    if (values == null) {
      return values;
    }
    int length = values.length;
    String[] escapseValues = new String[length];
    for (int i = 0; i < length; i++) {
      // 过滤一切可能的xss攻击字符串
      escapseValues[i] = Jsoup.clean(values[i], Whitelist.relaxed()).trim();
      // escapseValues[i] = HtmlUtils.htmlEscape(values[i], "UTF-8").trim();
      if (!StringUtils.equals(escapseValues[i], values[i])) {
        logger.debug("xss字符串过滤前：" + values[i] + "\r\n" + "过滤后：" + escapseValues[i]);
      }
    }
    return escapseValues;
  }
}
